
package shared.units;

import java.util.ArrayList;
import java.util.List;

import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;

public class BulletManager implements PhysicsCollisionListener {

	private BulletAppState bulletAppState;
	private Node node;
	private Material mat;

	private List<Bullet> bullets;

	public BulletManager(BulletAppState bulletAppState, Node rootNode, Material defaultMaterial) {
		this.bulletAppState = bulletAppState;
		this.node = rootNode;
		this.mat = defaultMaterial;
		this.bullets = new ArrayList<Bullet>();
		this.bulletAppState.getPhysicsSpace().addCollisionListener(this);
	}

	public void shootBullet(Vector3f position, Vector3f direction, float speed) {
		for (Bullet b : bullets) {
			if (!b.isInUse()) {
				b.activate(position, direction, speed);
				return;
			}
		}

		Bullet b = new Bullet(bulletAppState, node, mat);
		b.activate(position, direction, speed);
		bullets.add(b);
	}

	@Override
	public void collision(PhysicsCollisionEvent collisionEvent) {
		if (collisionEvent.getNodeA().getName().equals("Bullet")) {
			System.out.println("Collision of Bullet detected");
			final Spatial colNode = collisionEvent.getNodeA();

			for (Bullet b : bullets) {
				if (b.isInUse()) {
					if (b.geo.equals(colNode))
						System.out.println("Active bullet collided");
					b.deactivate();
					return;
				}
			}
		}
	}

}
